package com.larsgard.gedviewer.server.storage;

import java.util.ArrayList;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.larsgard.gedviewer.server.storage.entities.JDOUserTree;

public class TreeStorage extends Storage<JDOUserTree> {

    private static TreeStorage INSTANCE;

    private TreeStorage() {

    }

    public static TreeStorage getInstance() {
	if (INSTANCE == null) {
	    INSTANCE = new TreeStorage();

	}
	return INSTANCE;
    }

    public JDOUserTree storeTree(JDOUserTree tree) {
	if (tree.getKey() == null) {
	    tree.setKey(createKey(tree, tree.getTreeId(), null));
	}
	return super.storeObject(tree);
    }

    public JDOUserTree getTreeWithPassword(String password) {
	String filter = "password == '" + password + "'";
	ArrayList<JDOUserTree> objectList = super.getObjectList(JDOUserTree.class, 0, 1, null,
		filter);
	if (objectList.size() > 0) {
	    return objectList.get(0);
	}
	return null;
    }

    public ArrayList<JDOUserTree> getTreesForUser(String userMail) {
	String filter = "userMail == '" + userMail + "'";
	ArrayList<JDOUserTree> treeList = super.getObjectList(JDOUserTree.class, 0, 100, null,
		filter);
	return treeList;
    }

    public void deleteTree(JDOUserTree treeToDelete) {
	super.deleteObject(treeToDelete);
    }

    public JDOUserTree getTreesWithFileKey(String fileId) {
	String filter = "gedFileId == '" + fileId + "'";
	ArrayList<JDOUserTree> objectList = super.getObjectList(JDOUserTree.class, 0, 1, null,
		filter);
	if (objectList.size() > 0) {
	    return objectList.get(0);
	}
	return null;
    }

    public void deleteTree(String fileId) {
	JDOUserTree tree = getTreesWithFileKey(fileId);
	super.deleteObject(tree);
    }

    public void updateTreeProcessed(JDOUserTree tree) {

	PersistenceManager pm = PersistenceManagerFactory.getInstance().getPersistenceManager();

	Transaction tx = pm.currentTransaction();
	try {
	    tx.begin();
	    JDOUserTree persistentObject = pm.getObjectById(tree.getClass(), tree.getKey());
	    persistentObject.setProcessed(tree.getProcessed());
	    tx.commit();
	} catch (Exception e) {
	    if (tx.isActive()) {
		tx.rollback();
	    }

	} finally {
	    pm.close();
	}
    }
}
